package en.edu.zxj.rabbit.extensions.demo.config;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.TransactionManager;

/**
 * Created with IntelliJ IDEA.
 * Description：配置事务管理器
 *
 * @author: zxj
 * @date: 2024-09-21
 * @time: 21:39:05
 */
@Configuration
public class TransactionConfig {
    // 配置事务管理器, 该方法影响到注解 @Transactional 的使用
    @Bean("transactionManager")
    public TransactionManager transactionManager(CachingConnectionFactory cachingConnectionFactory) {
        return new RabbitTransactionManager(cachingConnectionFactory);
    }

    // 配置 RabbitTemplate, 只有使用了这个 rabbitTemplate 发送的消息才会开启事务
    @Bean("transRabbitTemplate")
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory cachingConnectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        rabbitTemplate.setChannelTransacted(true);
        return rabbitTemplate;
    }

    @Bean("transactionQueue")
    public Queue transactionQueue() {
        return QueueBuilder.durable("transactionQueue").build();
    }
}
